// pages/personal/checkCar/checkCar.js
import api from '../../../../utils/api'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isShow: false,
        isContact: false,
        submitCont: {
            adid: {}, //联系人信息,
            starttime: '', //预约日期
            time_area: '', //预约时间
            address: '', //取车经纬度
            addressname: '', //取车地点名
            carid: '', //车牌信息
            us_brief: '', //用户备注
            sure: '0', //用户确认
        },
        submitInfo: {}, //下单的数据
        popStartShow: false,
        popEndShow: false,
        minHour: 0,
        maxHour: 23,
        array: ['9:00-10:00', '10:00-11:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00', '16:00-17:00'],
        index: null,
        radioIndex: '1'
    },
    chooseAddr() {
        var that = this
        var location = this.data.submitCont.latlng
        location = location.split(',')
        var lat = location[1]
        var lng = location[0]
        wx.chooseLocation({
            latitude: lat,
            longitude: lng,
            success(res) {
                var latlng = res.longitude + ',' + res.latitude
                var data = {}
                data.to_address = res.address + '(' + res.name + ')'
                data.to_laglat = latlng
                data.type = that.data.radioIndex
                that.setFormData(data)
                that.setData({
                    "submitInfo.to_laglat": latlng,
                    "submitInfo.to_address": res.address + '(' + res.name + ')'
                })
            }
        })
    },
    onChange(event) {
        var data = {}
        if (event.detail == '1') {
            this.data.submitInfo.to_laglat = this.data.submitCont.latlng //还车地坐标
            this.data.submitInfo.to_address = this.data.submitCont.address //还车地地址
            data.to_laglat = this.data.submitCont.latlng
            data.to_address = this.data.submitCont.address
        } else {
            this.data.submitInfo.to_laglat = '' //还车地坐标
            this.data.submitInfo.to_address = '' //还车地地址
            data.to_laglat = ''
            data.to_address = ''
        }
        data.type = event.detail
        this.setFormData(data)
        this.setData({
            radioIndex: event.detail,
            submitInfo: this.data.submitInfo
        });
    },
    bindPickerChange: function (e) {
        //取车时间处理
        var time = this.data.array[e.detail.value]
        var end_time = time.split('-')[1]
        var et = end_time.split(':')[0]
        var nowTime = this.getNowTime('yearMonDay')
        var nowHour = this.getNowTime('hour')
        var nowDate = this.data.submitInfo.starttime
        if (nowDate) {
            if (nowTime.includes(nowDate)) {
                if (nowHour >= et) {
                    wx.showToast({
                        title: '时间已过',
                        icon: 'error'
                    })
                    return false
                }
            } else {

            }
        } else {
            wx.showToast({
                title: '请先选择日期',
                icon: 'error'
            })
            return false
        }
        var data = {}
        data.time_area = this.data.array[e.detail.value]
        data.index = e.detail.value
        this.setFormData(data)
        this.setData({
            index: e.detail.value,
            "submitInfo.time_area": this.data.array[e.detail.value]
        })
    },
    setFormData(data) {
        //选择完时间以及取车时间和异地还车应该要存进本地缓存中
        var datas = {}
        if (wx.getStorageSync('checkCar')) {
            datas = wx.getStorageSync('checkCar')
        }
        if (data.time_area) {
            datas.time_area = data.time_area
            datas.index = data.index
        }
        if (data.starttime) {
            datas.starttime = data.starttime
        }
        if (data.to_address) {
            datas.to_address = data.to_address
            datas.to_laglat = data.to_laglat
        }
        if (data.type) {
            datas.type = data.type
        }
        if (data.us_brief) {
            datas.us_brief = data.us_brief
        }
        wx.setStorageSync('checkCar', datas)
    },
    getNowTime(type) {
        // 获取当前时间内容
        var time = new Date()
        var hour = time.getHours()
        var year = time.getFullYear()
        var month = time.getMonth() + 1
        var day = time.getDate()
        var minutes = time.getMinutes()
        if (type == 'hour') {
            return hour
        } else if (type == 'allTime') {
            return `${year}年${month}月${day}日${hour}时${minutes}分`
        } else if (type == 'yearMonDay') {
            return `${year}-${month}-${day}`
        } else {
            return `${year}年${month}月${day}日${hour}时${minutes}分`
        }
    },
    formatDate(date) {
        date = new Date(date);
        return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    onConfirm(event) {
        var data = {}
        data.starttime = this.formatDate(event.detail)
        this.setFormData(data)
        this.setData({
            isShow: false,
            "submitInfo.starttime": this.formatDate(event.detail),
        });
    },
    onDisplay(e) {
        this.setData({
            isShow: true
        })
    },

    onClose() {
        this.setData({
            isShow: false
        })
    },
    formInp(e) {
        var data = {}
        data.us_brief = e.detail
        this.setFormData(data)
        this.setData({
            "submitInfo.us_brief": e.detail
        })
    },
    getContacts() {
        // 获取联系人内容
        let apis = api.api;
        var that = this
        let url = apis.host + 'Userdjorder/default_linkuser';
        let data = {};
        apis.request(url, data, 'POST').then(function (res) {
            if (res.code == 200) {
                const time = res.data.times
                time.min_time = time.min_time.substring(0, 2)
                time.max_time = time.max_time.substring(0, 2)
                time.dj_time_defalt = time.dj_time_defalt.substring(0, 2)
                if (res.data.default instanceof Array) {
                    that.setData({
                        isContact: true,
                        minHour: time.min_time,
                        maxHour: time.max_time,
                        currentDate: time.dj_time_defalt
                    })
                } else {
                    that.setData({
                        isContact: false,
                        submitCont: res.data.default,
                        minHour: time.min_time,
                        maxHour: time.max_time,
                        currentDate: time.dj_time_defalt
                    })
                }
            }
        }).catch(function (res) {
            console.log('订单开始失败', res)
        })
    },
    toCreate() {
        //跳转到创建联系人页面
        wx.redirectTo({
            url: '/pages/personal/checkCar/contactsMsg/index/index',
        })
    },
    submit() {
        //下单
        var that = this
        var apis = api.api
        var url = apis.host + 'Userdjorder/authcarindex';
        if (this.data.radioIndex == '2') {
            console.log('sadfsad')
            if (this.data.submitInfo.to_address == '') {
                wx.showToast({
                    title: '还车地址为空',
                    icon: 'error',
                })
                return false
            }
        } else {
            console.log('1212121')
            this.data.submitInfo.to_laglat = this.data.submitCont.latlng //还车地坐标
            this.data.submitInfo.to_address = this.data.submitCont.address //还车地地址
        }
        if (!this.data.submitInfo.starttime) {
            wx.showToast({
                title: '取车日期为空',
                icon: 'error',
            })
            return false
        }
        if (!this.data.submitInfo.time_area) {
            wx.showToast({
                title: '取车时间为空',
                icon: 'error',
            })
            return false
        }
        var data = this.data.submitInfo
        data.adid = this.data.submitCont.id
        data.sure = '0'
        console.log('dsfsafsadf', data)
        // return false
        wx.showModal({
            title: '提示',
            content: '确定下单？',
            success(res) {
                if (res.confirm) {
                    data.sure = '1'
                    apis.request(url, data, 'POST').then((res) => {
                        if (res.code == 200) {
                            let data = res.data.pay;
                            wx.showToast({
                                title: '下单成功',
                                icon: 'success',
                                success(res) {
                                    wx.requestPayment({
                                        timeStamp: data.timeStamp.toString(),
                                        nonceStr: data.nonce_str.toString(),
                                        package: 'prepay_id=' + data.prepay_id
                                            .toString(),
                                        signType: 'MD5',
                                        paySign: data.paySign.toString(),
                                        success(res) {
                                            wx.showToast({
                                                title: '支付成功',
                                                icon: 'success',
                                                success(res) {
                                                    wx.navigateTo({
                                                        url: '/pages/myOrder/index/index?type=' + 'checkCar',
                                                    })
                                                }
                                            })
                                        },
                                        fail(res) {
                                            wx.showToast({
                                                title: '支付失败，请重试！！',
                                                icon: 'none'
                                            })
                                        }
                                    })
                                }
                            })
                        } else {
                            wx.showModal({
                                title: '提示',
                                content: res.msg,
                            })
                        }
                    }).catch(function (res) {
                        wx.showModal({
                            title: '提示',
                            content: res.msg,
                        })
                    })
                } else {
                    wx.showToast({
                        title: '取消下单',
                        icon: 'error'
                    })
                }
            }
        })

    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options) {
            if (options.data) {
                options.data = JSON.parse(options.data)
                var userData = wx.getStorageSync('checkCar')
                if (userData) {
                    if (userData.index) {
                        this.data.index = userData.index
                        delete userData.index
                    }
                    if (userData.type) {
                        this.data.radioIndex = userData.type
                        delete userData.type
                    }
                }
                this.setData({
                    index: this.data.index,
                    radioIndex: this.data.radioIndex,
                    submitInfo: userData,
                    submitCont: options.data
                })
            } else {
                this.getContacts()
                var data = wx.getStorageSync('checkCar')
                if (data) {
                    if (data.index) {
                        this.data.index = data.index
                        delete data.index
                    }
                    if (data.type) {
                        this.data.radioIndex = data.type
                        delete data.type
                    }
                    this.setData({
                        index: this.data.index,
                        radioIndex: this.data.radioIndex,
                        submitInfo: data
                    })
                }
            }
            this.setData({
                options: options
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        var options = this.data.options

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})